package com.gzy.studentsociety.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * @version: java version 1.8
 * @Author: Chuan Liu
 * @description: 编码过滤器，统一处理请求和响应的字符编码
 * @date: 2024-11-16 23:21
 */
@WebFilter(filterName = "encodingFilter", urlPatterns = "/*",
        initParams = {@WebInitParam(name = "encoding", value = "UTF-8")})
public class encodingFilter implements Filter {
    private String encoding;

    @Override
    public void init(FilterConfig config) throws ServletException {
        this.encoding = config.getInitParameter("encoding");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        // 设置请求和响应的字符编码
        req.setCharacterEncoding(encoding);
        res.setCharacterEncoding(encoding);

        // 包装请求对象，处理参数编码
        HttpServletRequest wrappedRequest = new EncodingRequestWrapper(req, encoding);

        // 继续执行过滤链
        chain.doFilter(wrappedRequest, res);
    }

    @Override
    public void destroy() {
        // 空实现，无需销毁资源
    }

    /**
     * 自定义 HttpServletRequestWrapper，用于处理参数编码
     */
    private static class EncodingRequestWrapper extends HttpServletRequestWrapper {
        private final String encoding;

        public EncodingRequestWrapper(HttpServletRequest request, String encoding) {
            super(request);
            this.encoding = encoding;
        }

        @Override
        public String getParameter(String name) {
            String value = super.getParameter(name);
            return convertEncoding(value);
        }

        @Override
        public String[] getParameterValues(String name) {
            String[] values = super.getParameterValues(name);
            if (values == null) return null;
            for (int i = 0; i < values.length; i++) {
                values[i] = convertEncoding(values[i]);
            }
            return values;
        }

        @Override
        public Map<String, String[]> getParameterMap() {
            Map<String, String[]> paramMap = super.getParameterMap();
            for (Map.Entry<String, String[]> entry : paramMap.entrySet()) {
                String[] values = entry.getValue();
                for (int i = 0; i < values.length; i++) {
                    values[i] = convertEncoding(values[i]);
                }
            }
            return paramMap;
        }

        private String convertEncoding(String value) {
            if (value == null) return null;
            try {
                // 转换编码，防止乱码
                return new String(value.getBytes("ISO8859-1"), encoding);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return value; // 返回原值以避免出错
            }
        }
    }
}
